package com.simtop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.simtop.utils.FileUploadAndDownload;
import com.simtop.utils.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @author 文件上传下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    private Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private FileUploadAndDownload fileUploadAndDownload;

    @Value("${file.profile}")
    private String filePath;

    /**
     * 文件上传
     * @param files
     * @return
     */
    @PostMapping("/upload")
    public ResultBean upload(MultipartFile[] files, HttpServletRequest request){
        String[] arr = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            String richText = fileUploadAndDownload.upload2(files[i], "richText");
            arr[i] = richText;
        }
        return ResultBean.success(arr);
    }

    /**
     * 删除文件
     * @param data
     * @return
     */
    @PostMapping("/delete")
    public ResultBean upload(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONArray path = jsonObject.getJSONArray("path");
        try{
            for (Object o : path) {
                File file = new File(filePath + String.valueOf(o));
                file.delete();
            }
            log.info("删除项目文件成功");
            return ResultBean.success("删除成功");
        }catch (Exception e){
            log.info("删除项目文件失败");
            return ResultBean.error("删除失败");
        }
    }
}
